<template>
	<div  v-loading="loading">
		<div class="knowledge-set-test">
			  	<div class="knowledge-set-test-type">
			  		<template>
			  		  <el-radio-group v-model="question.testType" @change="tapChange">
			  		     <el-radio :label="1">手动录入</el-radio>
			  		     <el-radio :label="2">图片录入</el-radio>
			  		   </el-radio-group>
			  		</template>
			  	</div>

			  	<div class="knowledge-set-test-condition">
			  		 <template>
			  		 	<el-radio-group v-model="question.type" @change="setQuestionType">
			  		 		<template v-for="item of questionTypeList">
			  		 			<el-radio :label="item.id" :key="item.id">{{item.name}}</el-radio>
			  		 		</template>
			  		 	</el-radio-group>
			  		 </template>
			  	</div>
				
				<!--手动录入  -->
			  	<template v-if="question.testType == 1">
			  		<div class="knowledge-set-tes-txt">
			  			

			  			<div class="knowledge-operation">
			  					<span>题干<i>*</i></span>
			  					<div class="knowledge-">

			  						<vue-ueditor-wrap :config="config1" :destroy="true" v-model="question.stem" ref="ueditorStem" class="Ueditor-txt" ></vue-ueditor-wrap>
			  					</div>
			  			</div>

			  		</div>
			  	</template>

			  	<!-- 图片录入 -->
			  	<template v-if="question.testType  == 2">

			  		<div class="knowledge-set-tes-img">
			  			
			  			<div class="knowledge-up-img">
			  				<i class="el-icon-circle-close" @click="removeFile($event, 1)" v-show="uploadOptions.imageUrl"></i>
			  				<el-upload class="upload-demo" drag  :multiple="false"
			  				  :show-file-list="false" ref="upload"
			  				  :before-upload="beforeImageUrl"
			  				  :on-success="imageUrlSuccess"
			  				  :action="uploadOptions.target"
			  				  :headers="uploadOptions.headers"
			  				  accept=".jpg,.jpeg,.png,bmp"
			  				  :auto-upload="true">
			  				
			  				 <img v-show="uploadOptions.imageUrl" :src="uploadOptions.imageUrl" class="avatar">
			  				 
			  				  <template >
			  				  	<div class="knowledge-bg-img">
			  				  		<img src="../../../assets/images/upimg.png">
			  				  		<div>点击上传题目</div>
			  				  		<p>支持bmp/jpg/png/jpeg格式</p>
			  				  	</div>
			  				  </template>
			  				</el-upload>

			  			</div>

			  			<div class="knowledge-up-img">

			  				<i class="el-icon-circle-close" @click="removeFile($event, 2)" v-show="uploadOptions.resolveUrl"></i>
			  				<el-upload class="upload-demo" drag  :multiple="false"
			  				  :show-file-list="false"  ref="uploadResolve"
			  				  :before-upload="beforeResolveUrl"
			  				  :on-success="resolveUrSuccess"
			  				  :action="uploadOptions.target"
			  				  :headers="uploadOptions.headers"
			  				  accept=".jpg,.jpeg,.png, bmp"
			  				  :auto-upload="true">
			  				
			  				 <img v-show="uploadOptions.resolveUrl" :src="uploadOptions.resolveUrl" class="avatar">	
			  				 
			  				  <template >
			  				  	<div class="knowledge-bg-img">
			  				  		<img src="../../../assets/images/upimg.png">
			  				  		<div>点击上传解析</div>
			  				  		<p>支持bmp/jpg/png/jpeg格式</p>
			  				  	</div>
			  				  </template>
			  				</el-upload>

			  			</div>
			  		</div>	

			  	</template>
					<!-- 选择题 -->
			  	<template v-if="question.baseid == 1 || question.baseid == 2">

				  	<ul  v-show="question.testType == 1">
				  		<li class="knowledge-operation knowledge-outline" v-for="(option, key2) of question.options" :key="key2">
				  			<span>{{option.name}}<i>*</i></span>
				  			<div class="knowledge-">
                               
				  				<vue-ueditor-wrap :config="config1"  :destroy="true" :ref="`ueditor${key2}`" v-model="option.value" class="Ueditor-txt" ></vue-ueditor-wrap>
				  			</div>

				  			
				  		</li>
				  	</ul>
				  	<div class="answer-outline" v-if="question.testType == 1 && (question.baseid == 1 || question.baseid == 2 )">
				  		<span  v-preventReClick @click="removeAnswer(4)" v-show="question.baseid == 1 && question.answer.length < 4">
				  			<i class="el-icon-plus"></i>
				  			添加选项
				  		</span>
				  		<span  v-preventReClick @click="removeAnswer(4)" v-show="question.baseid == 2 && question.answer.length < 7">
				  			<i class="el-icon-plus"></i>
				  			添加选项
				  		</span>
				  		<span  v-preventReClick @click="removeAnswer(3)" v-show="question.answer.length > 2" >
				  			<i class="el-icon-minus"></i>
				  			移除选项
				  		</span>
				  	</div>


			  	  <div class="knowledge-operation">
			  			<span>答案: <i>*</i></span>
			  			<div class="knowledge- knowledge-choice">
			

			  				<el-radio-group v-model="question.check[0]" v-if="question.baseid == 1">
			  					<el-radio v-for="(answer, a) of question.answer" :label="answer" :key="a">{{answer}}</el-radio>
			  				</el-radio-group>

			  				<el-checkbox-group v-model="question.check"  v-if="question.baseid == 2">
			  				    <el-checkbox  v-for="(answer, b) of question.answer" :label="answer" :key="b">{{answer}}</el-checkbox>
			  				</el-checkbox-group>

			  				<div class="answer-choice" v-if="question.testType == 2">
			  					<i class="el-icon-remove-outline" v-preventReClick @click="removeAnswer(1)" v-show="question.answer.length > 2"></i>
			  					<i class="el-icon-circle-plus-outline" v-preventReClick @click="removeAnswer(2)"></i>
			  				</div>
			  			</div>
			  	  </div>
				 </template>

			  <div class="knowledge-operation" v-if="question.baseid == 3">
			  		<span>空位:<i>*</i></span>
			  		<div class="knowledge-vacancy">

			  			  <el-select v-model="question.blankNum" placeholder="请选择空位数">
			  			    <el-option
			  			      v-for="(item, index) in 10"
			  			      :key="index" :label="item"  :value="item">
			  			    </el-option>
			  			  </el-select>
			  		</div>
			  </div>
			
			<!-- 判断题 答案 -->
		    <div class="knowledge-operation" v-if="question.baseid == 4">
		  		<span>答案:<i>*</i></span>
		  		<div class="knowledge- knowledge-choice">
		  			<el-radio-group v-model="question.check[0]" >
		  				<el-radio label="对" >对</el-radio>
		  				<el-radio label="错" >错</el-radio>
		  			</el-radio-group>
		  		</div>
		  	</div>

		    <div class="knowledge-operation" v-show="question.testType == 1">
		  		<span>解析:<i>*</i></span>
		  		<div class="knowledge-">

		  			<vue-ueditor-wrap :config="config1" :destroy="true" ref="ueditorResolve" v-model="question.resolve" class="Ueditor-txt" ></vue-ueditor-wrap>
		  		</div>
		    </div>

			  <div class="knowledge-operation">
			  		<span>难度:<i>*</i></span>
			  		<div >
			  			<template>
						  <el-radio-group v-model="question.difficulty" >
						    <!-- <el-radio :label="0">全部</el-radio> -->
						    <el-radio :label="11">容易</el-radio>
						    <el-radio :label="12">普通</el-radio>
						    <el-radio :label="13">困难</el-radio>
						  </el-radio-group>
						</template>
			  		</div>
			  </div>

			  <div class="knowledge-operation">
			  		<span>重点程度:<i>*</i></span>
			  		<div >
			  			<template>
			  			  <el-radio-group v-model="question.keynote">
			  			    <el-radio :label="1">低</el-radio>
			  			    <el-radio :label="2">中</el-radio>
			  			    <el-radio :label="3">高</el-radio>
			  			  </el-radio-group>
			  			</template>  
			  		</div>
			  </div>

			  <div class="knowledge-operation" >
			  		<span>题目范围:<i>*</i></span>
                    <testArea ref="testArea" required :key="question.testType" @changeArea="changeArea"></testArea>
			  </div>

			  <div class="knowledge-operation">
			  		<span>章节:</span>
			  		<div >
			  			<el-cascader :options="chapterList"  placeholder= '选择章节'
			  			 filterable clearable
			  			 v-model="question.chapter"
                        @focus="setMaterial"
			  			@change="chapterChange">
			  			</el-cascader>
			  		</div>
			  </div>

			  <div class="knowledge-operation" >
			  		<span>知识点:</span>
			  		<div >
			  			<el-cascader :options="knowledgeList"  placeholder= '选择知识点'
			  			filterable clearable
			  			v-model="question.knowled"
						@focus="setMaterial"
			  			@change="knowledgeChange">
			  			</el-cascader>
			  		</div>
			  </div>



			  <div class="knowledge-operation knowledge-node-list">
			  		<span v-for="index of listArr" title="不可点击">{{index}}</span>
			  </div>

		  </div>

			
		  <span slot="footer" class="dialog-footer knowledge-btn">
		    <el-button v-preventReClick @click="preservationNext(1)" type="primary" plain>保存</el-button>
		    <el-button v-preventReClick type="primary"  @click="preservationNext(2)">保存并创建下一题</el-button>
		  </span>
	</div>
</template>


<script>
	import bus  from  './../base/eventBus.js'
    import VueUeditorWrap from 'vue-ueditor-wrap' // ES6 Module
    import testArea  from  './test-area';

	export default {
		components: { 
            VueUeditorWrap,
            testArea
        },
		data(){
			return{
				loading: true,
				value: '',
				reFresh:true,
				conditionType: 1,
				showVisible: false,
				settingsVisible: false,
				input: '',
				question: {
					id: '',
					testType: 1,/*1手动，2 图片*/
					type: 1, 		/*试题类型*/
					difficulty: 11,  /*难度*/
					keynote: 1,		/*重点程度*/
					grade: '', 		/*年级id*/
					subject: '',    /*科目id*/
					edition: '', 	/*版本id*/
					material: '',	/*教材*/
					blankNum: '',	/*空位*/
					resolve: '',	/*解析*/
					stem: '',	/*题干*/
					options: [{name: 'A', value: ''}, {name: 'B', value: ''}],
					chapter: '',	/*章节*/
					knowled: '',	/*知识点*/
					imageUrl: '',
					resolveUrl:'',
					check: ['A'],
					answer: ['A','B'],
					baseid: 1,
					typeid: 1
				},


				testList: [], 		/*试卷列表*/
				chapterList: [], 	/* 章节列表*/
				knowledgeList: [],	/*知识点*/
				questionTypeList: [],/*题型*/
				activeName: '1',
				filterText: '',
				filterText2: '',
				chapterID: [],		/*章节 & 知识点 选中的id*/
				knowledgeID: [],
				vacancyList: [],
				tinymceVal: '',

				defaultProps: {
					children: 'children',
					label: 'name'
				},
				

				customToolbar: [
					[{ list: "ordered" }, { list: "bullet" }],
					[{ 'color': [] }, { 'background': [] }], 
					['clean']
				],

				ChoiceArr: ['A','B','C','D','E','F','G'],//数组
				tabTempIndex: '1',

				/*上传*/
				uploadOptions: {
					imageUrl: '',
					resolveUrl: '',
					// target: this.BASE_URL + "/api/resource/res_upload",
					target: this.BASE_URL + "/api/resource/res_upload_permanent",
					headers: { Authorization: `Bearer ` + this.$g.access_token}
				},

				listArr: [],
				index: 0,
				questionID: 0,
				testList: [],
				testArray: [],
		        config1: {
		        	// zIndex: 3,
		        	textIndent: 0,
		        	maximumWords: 2000,
		        	elementPathEnabled: false,/*元素路径*/
		        	enableAutoSave: false,
					autoHeightEnabled: false,
					autoFloatEnabled: false,//不允许滚动时固定在顶部
					initialContent:'请输入内容...',   //初始化编辑器的内容,也可以通过textarea/script给值，看官网例子
					autoClearinitialContent:true, //是否自动清除编辑器初始内容，注意：如果focus属性设置为true,这个也为真，那么编辑器一上来就会触发导致初始化的内容看不到了
					initialFrameWidth: '100%',
					initialFrameHeight: 100,
					serverUrl: this.BASE_URL+"/static/_/UEditor/1.4.3/php/controller.php?action=uploadimage",
					BaseUrl: this.BASE_URL,
					UEDITOR_HOME_URL: process.env.BASE_URL ? process.env.BASE_URL + 'ueditor/' : '/static/ueditor/',
					toolbars: [
						['bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'pasteplain',  'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc','fullscreen',  'simpleupload','link', 'justifyleft', 'justifyright', 'justifycenter', 'lineheight', 'fontfamily', 'fontsize', 'undo', 'redo']
					]
                },
			}
		},
		created(){
			
		},
		mounted(){
			this.$nextTick(()=>{
				this.getQuestionType()
			});
        },

		methods: {
			/**
			 * 根据题型显示选择
			 * @qiu_m
			 * @DateTime 2019-12-04T17:18:57+0800
			 * @param    {[type]}                 val [description]
			 */
			setQuestionType(id){

				for (var i = 0; i < this.questionTypeList.length; i++) {
					if (this.questionTypeList[i].id == id ) {

						this.question.baseid = this.questionTypeList[i].base_id;
						this.question.typeid = this.questionTypeList[i].id
						break
					}
				}


				
				// this.question.stem = ''
				this.question.resolve = ''
				
				if (this.question.baseid == 1) {
					this.question.options = [{name: 'A', value: ''}, {name: 'B', value: ''}]
					this.question.answer = ['A','B']
					this.question.check = ['A']
				
				}else if (this.question.baseid == 2) {

					this.question.options = [{name: 'A', value: ''}, {name: 'B', value: ''}]
					this.question.answer = ['A','B']
					this.question.check = ['A']
				}else if(this.question.baseid == 4){

					this.question.options = [{name: '对', value: '对'}, {name: '错', value: '错'}]
					this.question.check = ['对']

				}else  {

					this.question.options = []
					this.question.answer = []
					this.question.check = []
				}
				this.$forceUpdate()

				// this.$children.forEach(item=>{
				// 	if (item.$el.className == 'Ueditor-txt') {
				// 		item.clearContentTxt()
				// 	}
				// })

				

				// this.clearContentTxt()
			},
			getTestList(){
				let success = (res=>{
					this.testList = res.data.question_list;

				});
				let params = ''
				if (this.$route.query.edit) {
					 params = {
						id: this.$route.query.edit,
						user_id: this.$g.user_id
					};
				}else if (this.$route.query.points) {
					 params = {
						id: this.$route.query.id,
						user_id: this.$g.user_id
					};
				}

				this.$ajax({
					url: 'api/newtest/test_detail',
					method: 'get',
					params: params,
					func: {success: success}
				})	
			},
			/**
			 * 保存
			 * @DateTime 2019-09-03T17:18:56+0800
			 * @return   {[type]}                 [description]
			 */
			preservation(){
                // 先验证试卷范围里的几个select框的值是否选择
                this.$refs.testArea.valid();
                let noSelect = Object.values(this.$refs.testArea.ruleForm).includes('');
                if(noSelect)return;

				sessionStorage.removeItem('addTS')
				if (this.$route.query.points) {
					bus.$emit('setTest', this.showVisible);
				}else{
					bus.$emit('showVisible2', this.showVisible);
				}
				

			},
			/**
			 * 保存并创建下一题
			 * @DateTime 2019-09-03T17:19:19+0800
			 * @return   {[type]}                 [description]
			 */
			preservationNext(type){



				let success = (res=>{


					this.questionID = res.data;
					
					this.$message.success(res.msg)
				
					/*新建试卷<div></div>的方法*/
					if (this.$route.name == 'knowledge-points') {
						this.getTestList()
						if (sessionStorage.getItem('addTS')) {

							setTimeout(() => {
								this.testChang()
							}, 400);
						}
					}


					this.uploadOptions.resolveUrl = '';
					this.uploadOptions.imageUrl = '';
			
					
                    this.$refs.testArea.reset();//重置题目范围

					this.question.type = 1
					this.question.testType = 1;/*1手动，2 图片*/
					this.question.baseid = 1; 		/*试题类型*/
					// this.question.difficulty = 11;  /*难度*/
					// this.question.keynote = 1;		/*重点程度*/

			
					this.question.blankNum = '';	/*空位*/
					this.question.resolve = '';	/*解析*/
					// this.question.answer = '';		/*答案*/
					this.question.stem = '';	/*题干*/
					this.question.options = [{name: 'A', value: ''}, {name: 'B', value: ''}];
					// this.question.chapter = [];	/*章节*/
					// this.question.knowled = [];	/*知识点*/
					this.question.imageUrl = '';
					this.question.resolveUrl ='';
					this.question.check = ['A'];
					this.question.answer = ['A','B'];

					// this.chapterList = [], 	/* 章节列表*/
					// this.knowledgeList = [],	/*知识点*/
					

					bus.$emit('addTest', this.question);

					if (type == 1) {
						sessionStorage.removeItem('addTS')
						if (this.$route.query.points) {
							bus.$emit('setTest', this.showVisible);
						}else{
							bus.$emit('showVisible2', this.showVisible);
						}
					}else{
						++this.index
						this.listArr.push(this.index)
					}

					setTimeout(() => {
						this.$store.commit('SET_QUESTIONCHANGE', new Date())
						this.reFresh = true
					}, 500);

				});

				/*图片录入*/
				if (this.question.testType == 2) {

					if (this.uploadOptions.imageUrl == '') {
						return this.$message.error('请上传题干图片...')
					}else if (this.uploadOptions.resolveUrl == '') {
						return this.$message.error('请上传解析图片...')
					}

					this.question.options = []
					if (this.question.baseid == 1 || this.question.baseid == 2 ) {
						
						this.question.answer.forEach(item =>{

							this.question.options.push({
								name: item,
								value: ''
							})
						})
					}else if(this.question.baseid == 4){
						this.question.options = [{name: '对', value: '对'}, {name: '错', value: '错'}]
					}else{
						this.question.options = []
					}


				}else{
					if (this.question.stem == '') {
						 return this.$message.error(`请填写题干内容`)
                    }else if(this.$refs.ueditorStem.editor.body.innerText.length > 2000){
                        return this.$message.error(`题干内容,已达到字数上限`)
                    }
                    
                    if (this.question.options.length != 0 && (this.question.baseid == 1 || this.question.baseid == 2)) {
						for (let k = 0; k < this.question.options.length; k++) {
                            let option = this.question.options[k];
                            let ueditor = 'ueditor' + k;
							if (option.value == '') {
								return this.$message.error(`请填写${option.name}选择题内容`)
                            }else if(this.$refs[ueditor][0].editor.body.innerText.length > 2000){
								return this.$message.error(`${option.name}选择题内容,已达到字数上限`)
                            }
						}
                    }
                    
                    if (this.question.resolve == ''){
						return this.$message.error(`请填写解析内容`)
                    }else if(this.$refs.ueditorResolve.editor.body.innerText.length > 2000){
                        return this.$message.error(`解释的内容,已达到字数上限`)
                    }
				}



				/*检验多选题答案不能为空*/
				if (this.question.baseid == 1 && this.question.check.length == 0) {
					return this.$message.error(`请勾选答案`)
				}else if (this.question.baseid == 2 && this.question.check.length == 0) {
					return this.$message.error(`请勾选答案`)
				}

				if ( this.question.baseid == 3 && this.question.blankNum == '') {
					return this.$message.error(`请选择空位`)
				}
		
        	    /*检验题目范围:不能为空*/
                this.$refs.testArea.valid();
                let noSelect = Object.values(this.$refs.testArea.ruleForm).includes('');
                if(noSelect)return;

				/*手动组卷 & 非单项，多项，判断题是选项为空数组*/
				if ( +this.question.testType == 1 && ![1, 2, 4].includes(+this.question.baseid)) {

					this.question.options = [];
				}

				/*非选择题时重置答案*/
				if (![1, 2, 4].includes(+this.question.baseid)) {
					this.question.check = null
				}

				

				/*1手动录入 2图片录入*/
				let [listid, knowid, chapterArr, knowledArr] = ['', '', '', ''];
				chapterArr = deep_clone(this.question.chapter)
				knowledArr = deep_clone(this.question.knowled)
				if (this.question.chapter.length != 0) {
					listid = chapterArr.pop()
				}
				if (this.question.knowled.length != 0) {
					knowid = knowledArr.pop()
				}

				/*非填空题清空空位*/
				if (this.question.baseid != 3) {
					this.question.blankNum = ''
				}

				let params = ''
				if (this.question.testType == 1) {
					 params = {
						// id: this.$route.query.id,
						pattern: this.question.testType,/*1手动录入 2图片录入*/
						type_id: this.question.typeid,/*题型id*/
						content: this.question.stem,/*题干*/
						resolve: this.question.resolve,/*解析*/
						option: this.question.options,/*选项 以数组形式 如 option[0]['name'] option[0]['value']*/
						answer: this.question.check,/*答案 以数组形式 如 anseer[0] answer[1]*/
						difficulty_id: this.question.difficulty,/*难度id*/
                        keynote: this.question.keynote,/*重点程度 1低 2中 3高*/
                        
                        grade_id: this.$refs.testArea.ruleForm.grade,
                        subject_id: this.$refs.testArea.ruleForm.subject,
                        version_id: this.$refs.testArea.ruleForm.edition,
                        masterial_id: this.$refs.testArea.ruleForm.material, 
                        
						list_id: listid,/*章节id*/
						know_id: knowid,/*知识点id*/
						blank_num: this.question.blankNum,/*填空题的空格数*/
						authority: 0,
					};
				}else{

					 params = {
						// id: this.$route.query.id,
						pattern: this.question.testType,/*1手动录入 2图片录入*/
						type_id: this.question.typeid,/*题型id*/

						content: this.question.imageUrl,/*题干*/
						resolve: this.question.resolveUrl,/*解析*/
						option: this.question.options,/*选项 以数组形式 如 option[0]['name'] option[0]['value']*/

						answer: this.question.check,/*答案 以数组形式 如 anseer[0] answer[1]*/
						difficulty_id: this.question.difficulty,/*难度id*/
                        keynote: this.question.keynote,/*重点程度 1低 2中 3高*/
                        

                        grade_id: this.$refs.testArea.ruleForm.grade,
                        subject_id: this.$refs.testArea.ruleForm.subject,
                        version_id: this.$refs.testArea.ruleForm.edition,
                        masterial_id: this.$refs.testArea.ruleForm.material, 

						list_id: listid,/*章节id*/
						know_id: knowid,/*知识点id*/
						blank_num: this.question.blankNum,/*填空题的空格数*/
						authority: 0
					};
				}

				this.$ajax.post('api/newtest/question', params, {func: {success: success}})

			},
			/**
			 * 试卷的试题排序
			 * @DateTime 2019-08-13T15:27:53+0800
			 * @return   {[type]}                 [description]
			 */
			testChang(){

				// console.log(this.testList,8)

				let [idex, questionList] = [1, []]

				if (this.testList.length != 0) {
					this.testList.forEach(item=>{
						questionList.push({
							'question_id': item.id,
							'score': item.score,
							'sort': idex++
						})
					})
				}


				questionList.push({
					'question_id': this.questionID,
					'score': 5,
					'sort': idex++
				})


				let success = (res=>{
					// this.$message.success(res.msg)
					// sessionStorage.removeItem('addTS')
					// this.submitTest()
				});

				let testID = ''

				if (this.$route.query.id) {
					testID = this.$route.query.id
				}else{
					testID = this.$route.query.edit
				}

				let params = {test_id: testID, question_list: questionList};
				this.$ajax.put('api/newtest/change_test', params, {func: {success: success}})
			},
			tapChange(val){
				// this.$refs.upload.uploadFiles = [];
				this.uploadOptions.imageUrl = '';
				
				// this.$refs.uploadResolve.uploadFiles = [];
				this.uploadOptions.resolveUrl = '';
				switch(val){
					case 1:			
						this.question.stem = ''
						this.question.resolve = ''
						// this.question.difficulty =  11;  /*难度*/
						// this.question.keynote =  1;		/*重点程度*/
						// this.question.grade =  ''; 		/*年级id*/
						// this.question.subject =  '';    /*科目id*/
						// this.question.edition =  ''; 	/*版本id*/
						// this.$refs.testArea.ruleForm.material =  '';	/*教材*/
						// this.question.chapter =  '';	/*章节*/
						// this.question.knowled =  '';	/*知识点*/
						this.question.img1 =  '';
						this.question.img2 =  '';
						this.question.check =  ['A'];
						this.question.answer =  ['A','B'];

					break;
					case 2:	
						this.question.resolve = ''	
						this.question.stem = '';		/*题干*/
						this.question.options = [{name: 'A', value: ''}, {name: 'B', value: ''}];/*选择题*/
						this.question.resolv =  ''; 		/*解析*/
						// this.question.difficulty =  11;  /*难度*/
						// this.question.keynote =  1;		/*重点程度*/
						// this.question.grade =  ''; 		/*年级id*/
						// this.question.subject =  '';    科目id
						// this.question.edition =  ''; 	/*版本id*/
						// this.$refs.testArea.ruleForm.material =  '';	/*教材*/
						// this.question.chapter =  '';	/*章节*/
						// this.question.knowled =  '';	/*知识点*/

					break;
				}

			},

			/**
			 * 文件上传时的钩子==解析
			 * @DateTime 2019-08-16T14:28:17+0800
			 * @param    {[type]}                 response [description]
			 * @param    {[type]}                 file     [description]
			 * @param    {[type]}                 fileList [description]
			 * @return   {[type]}                          [description]
			 */
			resolveUrSuccess(res, file){
				if (res.data.ecode == 200) {
					this.question.resolveUrl = res.data.file_path;
				}
			
			},
			/**
			 * 文件上传成功时的钩子==题干
			 * @DateTime 2019-08-16T14:27:58+0800
			 * @param    {[type]}                 res  [description]
			 * @param    {[type]}                 file [description]
			 * @return   {[type]}                      [description]
			 */
			imageUrlSuccess(res, file) {
				// console.log(res, file);
				if (res.data.ecode == 200) {
					this.question.imageUrl = res.data.file_path;
					// console.log(this.question.imageUrl);
				}
			},
			removeFile(e, type){
				if (type == 1) {
					this.$refs.upload.uploadFiles = [];
					this.uploadOptions.imageUrl = '';
				}else{
					this.$refs.uploadResolve.uploadFiles = [];
					this.uploadOptions.resolveUrl = '';
				}
			},
			beforeResolveUrl(file){

				let imgType = ['image/png', 'image/jpg', 'image/jpeg', 'image/bmp']

				if (!imgType.includes(file.type)) {
					this.$message.warning('请上传符合格式图片')
					return false
				}else if (file.size > 10480000 ) {
					this.$message.warning('只允许上传10M以内的图片');
					return false
				}else{
					this.uploadOptions.resolveUrl =  URL.createObjectURL(file);
				}
			
			},
			/**上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
			 * [handleBeforeUpload description]
			 * @DateTime 2019-08-16T14:27:14+0800
			 * @param    {[type]}                 file [description]
			 * @return   {[type]}                      [description]
			 */
			beforeImageUrl(file){
				/*let  matchList = file.name.toLocaleLowerCase().match(/.+(\.[a-zA-Z]+)/);
				let fileType = 	matchList?matchList[matchList.length - 1]:"";*/
				let imgType = ['image/png', 'image/jpg', 'image/jpeg', 'image/bmp']

				if (!imgType.includes(file.type)) {
					this.$message.warning('请上传符合格式图片')
					return false
				}else if (file.size > 10480000 ) {
					this.$message.warning('只允许上传10M以内的图片');
					return false
				}else{
					this.uploadOptions.imageUrl = URL.createObjectURL(file);
				}
			},
			/**
			 * [removeAnswer description]
			 * @DateTime 2019-09-02T16:55:19+0800
			 * @param    {[type]}                 obj  [description]
			 * @param    {[type]}                 type [description]
			 * @return   {[type]}                      [description]
			 */
			removeAnswer(type){

				var len = this.question.answer.length;
				let index = this.question.options.length;
				switch(type){
					case 1:
						if ( this.question.answer.length < 3) {return this.$message.error('不能再删除了....')}
						if ( this.question.baseid == 1 || this.question.baseid == 2)  {
							let a = this.question.answer.pop()
							for (let i = 0; i < this.question.check.length; i++) {
								let item = this.question.check[i]
								if ( a == item) {
									this.question.check.splice(i, 1)
								}
							}
						}
					break;
					case 2:
						if ( this.question.baseid == 1 &&  this.question.answer.length > 3) {
							return this.$message.error('不能再添加了....')
						}else if ( this.question.answer.length > 6) {
							return this.$message.error('不能再添加了....')
						}
						 this.question.answer.push(this.ChoiceArr[len])
					break;
					case 3:

						if ( this.question.options.length < 3) {return this.$message.error('不能再删除了....')}
						 	this.question.options.pop();
						 if ( this.question.baseid == 1 || this.question.baseid == 2)  {
						 	let a = this.question.answer.pop()
						 	for (let i = 0; i < this.question.check.length; i++) {
						 		let item = this.question.check[i]
						 		if ( a == item) {
						 			this.question.check.splice(i, 1)
						 		}
						 	}
						 }
							
					break;
					case 4:
			
						if ( this.question.baseid == 1 &&  this.question.options.length > 3) {
							return this.$message.error('不能再添加了....')
						}else if ( this.question.options.length > 6) {
							return this.$message.error('不能再添加了....')
						}
						 this.question.options.push({
							name: this.ChoiceArr[index],
							value: ''
						})
						this.question.answer.push(this.ChoiceArr[this.question.options.length-1])
					break;

				}

			},



			/**
			 * 请求题型数据
			 * @DateTime 2019-07-25T14:04:59+0800
			 * @return   {[type]}                 [description]
			 */
			getQuestionType(){

				let success = (res=>{
					this.questionTypeList = res.data;
					this.loading = false
				});

				let params = {status: 1};

				this.$ajax({
					url: 'api/newtest/get_question_type',
					method: 'get',
					params: params,
					func: { success: success}
				})
			},
			// 监听到试卷范围组件里面的值改变时，章节、知识点也改变
			changeArea(data){
				this.question.chapter =  '';
				this.question.knowled =  '';	
			},
			/**
			 * 获取章节选择的id
			 * @return {[type]} [description]
			 */
			chapterChange(val) {
			  this.question.chapter = deep_clone(val)
			},
			/**
			 * 获取知识点选择的id
			 * @DateTime 2019-09-04T11:42:45+0800
			 * @param    {[type]}                 val [description]
			 * @return   {[type]}                     [description]
			 */
			knowledgeChange(val){
				this.question.knowled = deep_clone(val)
			},
			/**
			 * 请求章节数据
			 * @DateTime 2019-07-23T14:04:49+0800
			 * @return   {[type]}                 [description]
			 */
			getChapter(){
				if (this.$refs.testArea.ruleForm.material === '') {return};

				let success = (res=>{
					this.chapterList  = []

					res.data.forEach((item, index)=>{
						this.chapterList.push({
							value: item.id,
							label: item.name,
							children: []
						})

						if (item.children.length != 0) {

							item.children.forEach(child=>{
								this.chapterList[index].children.push({
									value: child.id,
									label: child.name
								})
							})
						}else{
							this.$set(this.chapterList[index], 'disabled', true)
						}


					})
				});

				let params = {}

				 params = {
					material_id: this.$refs.testArea.ruleForm.material,
					type: 1
				};

				let fail = (res=>{
					this.$message.error({
						duration: 8000,
						message: res.msg
					})
				})

				this.$ajax({
					url: 'api/newtest/get_list_know_by_material',
					method: 'get',
					params: params,
					func: {success: success, fail: fail}
				})
			},
			/**
			 * 请求章知识点数据
			 * @DateTime 2019-07-23T14:04:49+0800
			 * @return   {[type]}                 [description]
			 */
			getKnowledge(){
				if (this.$refs.testArea.ruleForm.material === '') {return};

				let success = (res=>{
					this.knowledgeList  = []

					res.data.forEach((item, index)=>{
						this.knowledgeList.push({
							value: item.id,
							label: item.name,
							children: []
						})

						if (item.children.length != 0) {

							item.children.forEach(child=>{
								this.knowledgeList[index].children.push({
									value: child.id,
									label: child.name
								})
							})
						}else{
							this.$set(this.knowledgeList[index], 'disabled', true)
						}


					})
				});

				let params = {}

				 params = {
					material_id: this.$refs.testArea.ruleForm.material,
					type: 2
				};

				let fail = (res=>{
					this.$message.error({
						duration: 8000,
						message: res.msg
					})
				})

				this.$ajax({
					url: 'api/newtest/get_list_know_by_material',
					method: 'get',
					params: params,
					func: {success: success, fail: fail}
				})
			},

			/**
			 * 判断教材是否为空，在不为空时，根据id筛选相关的试题
			 * @DateTime 2019-07-24T09:27:20+0800
			 * @param    {[Strong]}   val 教材id
			 */
			setMaterial(){
				if (this.$refs.testArea.ruleForm.material != '') {
					this.getChapter()
					this.getKnowledge()
				}else{
					this.$refs.testArea.ruleForm.material = ''
					this.question.chapter =  '';	/*章节*/
					this.question.knowled =  '';	/*知识点*/
					this.chapterID = [];
					this.knowledgeID = [];
					this.chapterList =  [] 	/* 章节列表*/
					this.knowledgeList = []	/*知识点*/
				}

			},

		}
	}
</script>
